package com.ruoyi.web.controller.warning;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.warning.domain.entity.Config;
import com.ruoyi.warning.domain.entity.Device;
import com.ruoyi.warning.domain.entity.Firewall;
import com.ruoyi.warning.domain.query.FirewallQuery;
import com.ruoyi.warning.service.IConfigService;
import com.ruoyi.warning.service.IDevicesService;
import com.ruoyi.warning.service.IFirewallService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 防火墙相关 前端控制器
 * </p>
 *
 * @author chenhc
 * @since 2025-07-23
 */
@RestController
@RequestMapping("/firewall")
@Api(tags = "防火墙", description = "用于处理防火墙相关操作的控制器")
public class FirewallController {

    @Resource
    private IFirewallService firewallService;
    @Resource
    private IConfigService configService;
    @Resource
    private IDevicesService devicesService;

    @ApiOperation("分页获取防火墙")
    @GetMapping(value = "/getPage")
    public R getPage(FirewallQuery query)
    {
        Page<Firewall> page = PageHelper.startPage(query.getPageNum(),query.getPageSize());
        List<Firewall> list = firewallService.list(new QueryWrapper<Firewall>().lambda());
        TableDataInfo tableDataInfo = new TableDataInfo(list, page.getTotal());
        return R.ok(tableDataInfo);
    }

    @ApiOperation("新增或更新防火墙")
    @GetMapping(value = "/addFirewall")
    public R addFirewall(String hostname)
    {
        return R.ok(firewallService.addFirewall(hostname));
    }

    @Anonymous
    @ApiOperation("防火墙绑定设备ping")
    @GetMapping(value = "/addFirewallDivcePing")
    public R addFirewallDivcePing(@RequestParam("ids") List<String> ids)
    {
//        firewallService.addFirewallDivcePing(hostnames);
        List<Device> list = devicesService.list(new QueryWrapper<Device>().lambda()
                .in(Device::getDeviceId,ids));
        list.stream().forEach(device -> device.setPingMonitor(1));
        devicesService.updateBatchById(list);

        Config config = configService.getOne(new QueryWrapper<Config>().lambda().eq(Config::getConfigName,"ping_monitor"));
        if(ObjectUtils.isEmpty( config))config = new Config();
        config.setConfigName("ping_monitor");
        config.setConfigValue(String.join(",", ids));
        configService.saveOrUpdate(config);
        return R.ok("OK");
    }

    @Anonymous
    @PostMapping(value = "/exportPing")
    public void exportPing(@ModelAttribute FirewallQuery query,HttpServletResponse response) throws IOException {
        List<LinkedHashMap<String, Object>> list = firewallService.getping(query);
        Config config = configService.getOne(new QueryWrapper<Config>().lambda().eq(Config::getConfigName,"ping_monitor"));
        String[] sz = config.getConfigValue().split(",");
        List<Device> list1 = devicesService.list(new QueryWrapper<Device>().lambda()
                .in(Device::getDeviceId,sz));
        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("Ping监控数据");

        // 创建标题行（如果列表不为空）
        if (!list.isEmpty()) {
            Row headerRow = sheet.createRow(0);
            Map<String, Object> firstRow = list.get(0);
            int cellIndex = 0;
            Cell cell = headerRow.createCell(cellIndex++);
            cell.setCellValue("时间");

            // 创建标题
            for (Device device : list1) {
                cell = headerRow.createCell(cellIndex++);
                cell.setCellValue(device.getHostname());
            }

            // 填充数据行
            for (int i = 0; i < list.size(); i++) {
                Row row = sheet.createRow(i + 1);
                Map<String, Object> dataRow = list.get(i);
                cellIndex = 0;

                for (String key : firstRow.keySet()) {
                    cell = row.createCell(cellIndex++);
                    Object value = dataRow.get(key);
                    if (value != null) {
                        cell.setCellValue(value.toString());
                    } else {
                        cell.setCellValue(""); // 或者设置为默认值
                    }
                }
            }
            // 自动调整列宽
            for (int i = 0; i < firstRow.size(); i++) {
                sheet.autoSizeColumn(i);
            }
        }

        // 设置响应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition", "attachment; filename=ping_monitor_data.xlsx");

        // 写入响应输出流
        workbook.write(response.getOutputStream());
        workbook.close();
    }

    @ApiOperation("获取所有设备的ping")
    @GetMapping(value = "/getPing")
    public R getPing(FirewallQuery query){
        return R.ok(firewallService.getping(query));
    }
}
